package com.wjk.kylin.modules.generator.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.core.utils.SecurityUtils;
import com.wjk.kylin.modules.generator.constants.GenConstants;
import com.wjk.kylin.modules.generator.entity.GenTable;
import com.wjk.kylin.modules.generator.entity.GenTableColumn;
import com.wjk.kylin.modules.generator.mapper.GenTableMapper;
import com.wjk.kylin.modules.generator.service.IGenTableColumnService;
import com.wjk.kylin.modules.generator.service.IGenTableService;
import com.wjk.kylin.modules.generator.util.GenUtils;
import com.wjk.kylin.modules.generator.util.VelocityInitializer;
import com.wjk.kylin.modules.generator.util.VelocityUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * <p>
 * 业务表 服务实现类
 * </p>
 *
 * @author wangjkui
 * @since 2020-06-07
 */
@Service
@Transactional(readOnly = true)
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements IGenTableService {

    @Autowired
    private IGenTableColumnService genTableColumnService;

    @Override
    public IPage<GenTable> findPage(Page<GenTable> page, GenTable genTable) {
        return baseMapper.findPage(page, genTable);
    }

    @Override
    public IPage<GenTable> findDbPage(Page<GenTable> page, GenTable genTable) {
        return baseMapper.findDbPage(page, genTable);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean update(GenTable genTable) {

        this.validateEdit(genTable);

        genTable.setOptions(JSON.toJSONString(genTable.getParams()));

        boolean flag = super.updateById(genTable);

        if (flag) {
            genTableColumnService.updateBatchById(genTable.getColumns());
        }

        return flag;
    }

    @Override
    @Transactional(readOnly = false)
    public boolean deleteByIds(String[] tableIds) {

        boolean flag = super.removeByIds(Arrays.asList(tableIds));

        if (flag) {

            QueryWrapper<GenTableColumn> wrapper = new QueryWrapper<>();
            wrapper.in("table_id", Arrays.asList(tableIds));

            genTableColumnService.remove(wrapper);
        }

        return flag;
    }

    @Override
    public Map<String, Object> previewCode(String tableId) {
        Map<String, Object> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = super.getById(tableId);

        table.setColumns(genTableColumnService.findListByTableId(tableId));

        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

//    @Override
//    public byte[] downloadCode(String tableName) {
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        ZipOutputStream zip = new ZipOutputStream(outputStream);
//        generatorCode(tableName, zip);
//        IOUtils.closeQuietly(zip);
//        return outputStream.toByteArray();
//    }

    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    @Override
    @Transactional(readOnly = false)
    public void importGenTable(String[] tableNames) {

        List<GenTable> dbTableList = baseMapper.findDbTableListByNames(tableNames);

        for (GenTable table : dbTableList) {
            String tableName = table.getTableName();
            GenUtils.initTable(table);
            boolean flag = super.save(table); //保存表信息
            if (flag) {
                // 保存列信息
                List<GenTableColumn> genTableColumns = genTableColumnService.findDbTableColumnsByName(tableName);
                for (GenTableColumn column : genTableColumns) {
                    GenUtils.initColumnField(column, table);
                    genTableColumnService.save(column);
                }
            }
        }
    }

    @Override
    public GenTable getById(String id) {
        GenTable genTable = super.getById(id);

        setTableFromOptions(genTable);

        genTable.setColumns(genTableColumnService.findListByTableId(id));

        return genTable;
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
        if (ObjectUtils.isNotEmpty(paramsObj)) {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

//    @Override
//    public void generatorCode(String[] tableName) {
//        // 查询表信息
//        GenTable table = super.getOne(new QueryWrapper<GenTable>().eq("table_name", tableName));
//        // 查询列信息
//        List<GenTableColumn> columns = table.getColumns();
//        setPkColumn(table, columns);
//
//        VelocityInitializer.initVelocity();
//
//        VelocityContext context = VelocityUtils.prepareContext(table);
//
//        // 获取模板列表
//        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
//        for (String template : templates) {
//            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
//                // 渲染模板
//                StringWriter sw = new StringWriter();
//                Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
//                tpl.merge(context, sw);
//                try {
//                    String path = getGenPath(table, template);
//                    FileUtils.writeStringToFile(new File(path), sw.toString(), GenConstants.UTF8);
//                } catch (IOException e) {
//                    log.error("渲染模板失败，表名：" + table.getTableName(), e);
//                    throw new BusinessException("渲染模板失败，表名：" + table.getTableName());
//                }
//            }
//        }
//    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = super.getOne(new QueryWrapper<GenTable>().eq("table_name", tableName));
        // 查询列信息
        List<GenTableColumn> columns = table.getColumns();
        setPkColumn(table, columns);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, GenConstants.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, GenConstants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
                throw new BusinessException("渲染模板失败，表名：" + table.getTableName());
            }
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
//    public static String getGenPath(GenTable table, String template) {
//        String genPath = table.getGenPath();
//        if (StringUtils.equals(genPath, "/")) {
//            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
//        }
//        return genPath + File.separator + VelocityUtils.getFileName(template, table);
//    }

    /**
     * 验证数据
     *
     * @param genTable
     */
    public void validateEdit(GenTable genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSONObject.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSONObject.parseObject(options);
            if (StringUtils.isBlank(paramsObj.getString(GenConstants.TREE_CODE))) {
                throw new BusinessException("树编码字段不能为空");
            } else if (StringUtils.isBlank(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
                throw new BusinessException("树父编码字段不能为空");
            } else if (StringUtils.isBlank(paramsObj.getString(GenConstants.TREE_NAME))) {
                throw new BusinessException("树名称字段不能为空");
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table   业务表信息
     * @param columns 业务字段列表
     */
    public void setPkColumn(GenTable table, List<GenTableColumn> columns) {
        for (GenTableColumn column : columns) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (ObjectUtils.isNull(table.getPkColumn())) {
            table.setPkColumn(columns.get(0));
        }
    }


}
